package com.saxon.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class CheckCode extends HttpServlet {
    @Override
    protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader ("refresh", "5");
        //图片的大小。
        BufferedImage image = new BufferedImage (80, 20, BufferedImage.TYPE_INT_RGB);
        Graphics2D pen = (Graphics2D) image.getGraphics ();
        //对图片进行填充
        pen.setColor (Color.black);
        pen.fillRect (0,0,80,20);
        //在图片中写入文字
        pen.setColor (Color.white);
        pen.setFont (new Font (null,Font.BOLD,20));
        pen.drawString (Num (),0,20);
        //浏览器的读取形式
        resp.setContentType ("image/jpeg");
        //缓存
        resp.setDateHeader ("expires",-1);
        resp.setHeader ("Cache-Control","no-cache");
        resp.setHeader ("pragma","no-cache");
        //图片交给浏览器
        ImageIO.write (image,"jpeg",resp.getOutputStream ());

    }

    private String Num(){
        StringBuffer str=new StringBuffer ();
        for (int i = 0; i <7 ; i++) {
            int i1 = new Random ().nextInt (9);
            str.append (i1);
        }
        return str.toString ();
    }
    @Override

    protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet (req, resp);
    }
}
